uniform vec3 eyePosition;
uniform float time;
uniform float centerX;
uniform float centerY;
uniform float WavePeriod;


varying vec3 lightVec;

varying mat3 rotMatrix; //  transform from tangent to obj space
varying vec2 bumpCoord0;
varying vec2 bumpCoord1;
varying vec2 bumpCoord2;
varying vec3 eyeVector;

const float PI = 3.1415926535897932384626433832795;
const float G = 9.81;
float c = WavePeriod*WavePeriod / 46.08;
float a = c * 2 / sqrt(5.0);
float b = 0.5 * a;
float omega = 2 * PI / WavePeriod;
float k = -omega*omega / G;

float waveFunction(float x, float z)
{
	return a*sin(k*(x+centerX) + omega*time) + b*cos(k*(x+centerX) + omega*time);
}

float waveFunDeriv(float x, float z)
{
	return a*k*cos(k*(x+centerX) + omega*time) - b*k*sin(k*(x+centerX) + omega*time);
}

void main(void)
{
	float BumpScale = 3.0;
	vec2 textureScale = vec2(8.0, 8.0);
	vec2 bumpSpeed = vec2(0.0, 0.0);

	vec4 P = gl_Vertex;
	
	P.y = waveFunction(P.x, P.z);
	float ddx = waveFunDeriv(P.x, P.z);
	float ddy = 0.0;
	

	// compute the 3x3 tranform from tangent space to object space
	// compute tangent basis
    vec3 T = normalize(vec3(1.0, ddy, 0.0)) * BumpScale;
    vec3 B = normalize(vec3(0.0, ddx, 1.0)) * BumpScale;
    vec3 N = normalize(vec3(ddx, 1.0, ddy));
    
    vec3 light = normalize(vec3(gl_LightSource[0].position));
	lightVec.x = dot(light, T);
	lightVec.y = dot(light, B);
	lightVec.z = dot(light, N);

	rotMatrix = mat3(T, B, N);

	gl_Position = gl_ModelViewProjectionMatrix * P;
	
	vec2 texCoords = vec2((P.x + 20.0)/40, (P.z + 20.0)/40);

	// calculate texture coordinates for normal map lookup
	bumpCoord0.xy = texCoords * textureScale + vec2(centerX*0.02, centerY*0.02);//time * bumpSpeed;
	bumpCoord1.xy = texCoords* textureScale * 2.0 + vec2(centerX*0.02, centerY*0.02) * 4.0;
	bumpCoord2.xy = texCoords * textureScale * 4.0 + vec2(centerX*0.02, centerY*0.02) * 8.0;


	eyeVector = P.xyz - eyePosition; // eye position in vertex space
}